package com.alisls.demo.springcloud.service.im.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.net.URI;
import java.util.Map;

/**
 * 握手拦截器
 *
 * @author Ke Wang
 * @date 2020/10/14
 */
@Component
@Slf4j
public class MyHandshakeInterceptor implements HandshakeInterceptor {

    /**
     * 握手之前，返回true将建立连接，false将不会建立连接
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
                                   WebSocketHandler webSocketHandler, Map<String, Object> attributes) throws Exception {
        log.info("开始握手");

        String path = serverHttpRequest.getURI().getPath();
        String id = getId(path);

        // 将用户id放入socket处理器的会话(WebSocketSession)中
        attributes.put("id", id);

        return true;
    }

    /**
     * 握手之后
     */
    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
                               WebSocketHandler webSocketHandler, Exception e) {
        log.info("握手完成");
    }

    private String getId(String path) {
        if (path == null || path.trim().length() <= 0) {
            throw new RuntimeException("请求路径不能为空！");
        }

        String id = path.substring(path.lastIndexOf("/"));
        if (id == null || id.trim().length() <= 0) {
            throw new RuntimeException("用户ID不能为空!");
        }
        return id;
    }
}

